package com.wei.interceptor;

import com.wei.model.HistoryUrlsDO;
import com.wei.service.IHistoryUrlsService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/*
*  创建拦截器
* */
@Component("historyUrlsInterceptor")
@RequiredArgsConstructor
public class HistoryUrlsInterceptor implements HandlerInterceptor {

    private final IHistoryUrlsService historyUrlsService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String url = request.getRequestURL().toString();
        String method = request.getMethod();

        // 只记录访问页面
        if (isPageRequest(request)) {
            System.out.println("记录页面访问: " + url);

            HistoryUrlsDO historyUrlsDO = new HistoryUrlsDO();
            historyUrlsDO.setUrl(url);
            historyUrlsDO.setVisitTime(new Date());
            historyUrlsService.save(historyUrlsDO);
        }
        return true;
    }

    private boolean isPageRequest(HttpServletRequest request) {
        String url = request.getRequestURL().toString();
        String method = request.getMethod();

        // 排除API请求
        if (url.contains("/api/") || url.contains("/error")) {
            return false;
        }

        // 只记录GET请求
        if (!"GET".equalsIgnoreCase(method)) {
            return false;
        }

        // 排除静态资源
        if (url.contains(".css") || url.contains(".js") || url.contains(".jpg") ||
                url.contains(".png") || url.contains(".ico") || url.contains(".pdf")) {
            return false;
        }

        return true;
    }
}
